<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图品懒加载</title>
    <style>
      .box {
        width: 600px;
        margin: 0 auto;
      }
      img {
        width: 100%;
        height: 600px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <img data-src="./images/fm1.jpg" alt="" />
      <img data-src="./images/fm2.jpg" alt="" />
      <img data-src="./images/fm3.jpg" alt="" />
      <img data-src="./images/fm4.jpg" alt="" />
      <img data-src="./images/fm5.jpg" alt="" />
      <img data-src="./images/fm6.jpg" alt="" />
      <img data-src="./images/fm7.jpg" alt="" />
      <img data-src="./images/fm8.jpg" alt="" />
      <img data-src="./images/fm9.jpg" alt="" />
      <img data-src="./images/fm10.jpg" alt="" />
      <img data-src="./images/fm11.jpg" alt="" />
    </div>
    <script>
      let imgs = [...document.querySelectorAll("img")];
      let length = imgs.length;

      const imageLazyLoad = () => {
        let count = 0; // 记录已经加载的图片数量
        return (function () {
          let deleteIndexList = []; // 缓存已经加载过的index
          imgs.forEach((img, index) => {
            const rect = img.getBoundingClientRect();
            // outerHeight (包含收藏栏，地址栏等高度)
            // innerHeight 浏览器(不包含收藏栏，地址栏等高度)
            if (rect.top < window.innerHeight) {
              img.src = img.dataset.src;
              count++;
              deleteIndexList.push(index);
              if (count === length) {
                document.removeEventListener("scroll", imageLazyLoad);
              }
            }
          });
          // 删除掉已经加载过的图片
          imgs = imgs.filter((img, index) => !deleteIndexList.includes(index));
        })();
      };
      imageLazyLoad(); // 首次加载
      document.addEventListener("scroll", imageLazyLoad); // 监听页面滚动
    </script>
  </body>
</html>
